import { queryCategory } from "@/api/service/classify/classify";
import { queryField } from "@/api/service/field/field";
import { delGoods, getGoods, listGoods } from "@/api/service/goods/goods";
import { ENUM_DATA_SCOPE } from "@/enum/system.enum";
import { toCamelCase } from "@/utils/format";
import { extendsFields, fileList, form, resetForm, showGoods } from "./form";
import { categoryList, query, selectedKeys, table } from "./table";

export const getList = async () => {
  table.value.loading = true;
  const res = await listGoods({
    ...query.value
  });
  table.value.data = res.rows;
  query.value.total = res.total;
  table.value.loading = false;

  const { data: fields } = await queryField();

  table.value.data = table.value.data.map((e) => {
    if (e.expands) {
      e.expands.forEach((v: any) => {
        const target = fields.find((m: any) => {
          if (m.fieldId === v.fieldId) {
            return m;
          }
          return null;
        });
        if (!target) return;
        e[toCamelCase(target.fieldCode)] = v.value;
      });
    }
    return e;
  });
};
export const pageChange = (index: number) => {
  query.value.pageNum = index;
  getList();
};
export const delByIds = async (id?: any) => {
  let ids = [];
  if (id) {
    ids = [id];
  } else {
    ids = selectedKeys.value;
  }
  await delGoods(ids);
  getList();
  selectedKeys.value = [];
};
export const editItem = async (item?: any) => {
  let config = "";
  if (!item) {
    config = selectedKeys.value[0] as any;
  } else {
    config = item.goodsId;
  }
  showGoods.value = true;
  const res = await getGoods(config);

  form.value = {
    ...res.data,
    barCode: res.data.barCode
  };
  form.value.disable = item.disable;
  fileList.value.push(form.value.goodsPhoto);
};
export const search = () => {
  query.value.pageNum = 1;
  getList();
};
export const create = () => {
  resetForm();
  form.value.expands = extendsFields.value;
  showGoods.value = true;
};
export const getCateGoryList = async () => {
  const data = await queryCategory({
    scope: ENUM_DATA_SCOPE.THIS_SHOP
  });
  categoryList.value = data.data.map((e: any) => {
    return {
      label: e.categoryName,
      value: e.categoryName
    };
  });
};
